package com.yun.redis.practice.twitter.controller;

import com.yun.redis.practice.RedisLock;
import com.yun.redis.practice.RedisUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lsy
 * on 2019/12/11 18:40.
 */
public class UserController {

    public boolean createUser(String login, String userName) {
        login = login.toLowerCase();
        Jedis conn = RedisUtils.getConnection();
        String token = RedisLock.acquire("user:" + login, 10);
        if (token == null) {
            // 未获得锁
            return false;
        }
        Map<String, String> user = conn.hgetAll("user:" + login);
        if (!user.isEmpty()) {
            conn.hincrBy("user:" +login, "flowing", 1);
            conn.hset("user:" +login, "signUp", System.currentTimeMillis() + "");
            // 已经创建了
            RedisLock.release("user:" + login, token);
            return false;
        }
        Long id = conn.incr("user:id:");
        Transaction tran = conn.multi();
        tran.hset("users:", login, id + "");
        HashMap<String, String> userModel = new HashMap<>();
        userModel.put("id", id + "");
        userModel.put("name", userName);
        userModel.put("flowers", "0");
        userModel.put("flowing", "0");
        userModel.put("posts", "0");
        userModel.put("signup", System.currentTimeMillis() + "");
        tran.hmset("user:" + login, userModel);
        List<Object> exec = tran.exec();
        if (exec != null) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        boolean b = new UserController().createUser("cs80", "shaoyunLv80");
        System.out.println(b);
    }
}
